package com.lx.tldoj.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.lx.tldoj.annotation.AuthCheck;
import com.lx.tldoj.common.BaseResponse;
import com.lx.tldoj.common.DeleteRequest;
import com.lx.tldoj.common.ErrorCode;
import com.lx.tldoj.common.ResultUtils;
import com.lx.tldoj.constant.UserConstant;
import com.lx.tldoj.exception.BusinessException;
import com.lx.tldoj.exception.ThrowUtils;
import com.lx.tldoj.model.dto.competition.*;

import com.lx.tldoj.model.entity.Competition;
import com.lx.tldoj.model.entity.CompetitionJoin;
import com.lx.tldoj.model.entity.User;
import com.lx.tldoj.model.vo.CompetitionVO;
import com.lx.tldoj.service.CompetitionJoinService;
import com.lx.tldoj.service.CompetitionService;
import com.lx.tldoj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.lx.tldoj.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 题目接口
 */
@RestController
@RequestMapping("/competition")
@Slf4j
public class CompetitionController {

    @Resource
    private CompetitionService competitionService;

    @Resource
    private UserService userService;

    @Resource
    CompetitionJoinService competitionJoinService;



    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param competitionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addCompetition(@RequestBody CompetitionAddRequest competitionAddRequest, HttpServletRequest request) {
        if (competitionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User currentUser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        Competition competition = new Competition();
        BeanUtils.copyProperties(competitionAddRequest, competition);
        competition.setCreatorId(currentUser.getId());
        boolean result = competitionService.save(competition);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newCompetitionId = 0L;
        return ResultUtils.success(newCompetitionId);
    }

    @PostMapping("/join")
    public BaseResponse joinCompetition(@RequestBody CompetitionAddRequest competitionAddRequest, HttpServletRequest request) {
        if (competitionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User currentUser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        QueryWrapper<CompetitionJoin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contestId", competitionAddRequest.getId());
        queryWrapper.eq("userId", currentUser.getId());
        List<CompetitionJoin> exist = competitionJoinService.list(queryWrapper);
        if(!exist.isEmpty()) {
            return ResultUtils.error(400, "不能重复参加竞赛");
        }
        CompetitionJoin competitionJoin = new CompetitionJoin();
        competitionJoin.setContestId(competitionAddRequest.getId());
        competitionJoin.setUserId(currentUser.getId());
        competitionJoin.setStatus(1);
        boolean result = competitionJoinService.save(competitionJoin);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newCompetitionJoinId = competitionJoin.getId();
        return ResultUtils.success(newCompetitionJoinId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteCompetition(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Competition oldCompetition = competitionService.getById(id);
        ThrowUtils.throwIf(oldCompetition == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldCompetition.getCreatorId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = competitionService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param competitionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateCompetition(@RequestBody CompetitionUpdateRequest competitionUpdateRequest) {
        if (competitionUpdateRequest == null || competitionUpdateRequest.getContestId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Competition competition = new Competition();
        BeanUtils.copyProperties(competitionUpdateRequest, competition);
        // 参数校验
        competitionService.validCompetition(competition, false);
        long id = competitionUpdateRequest.getContestId();
        // 判断是否存在
        Competition oldCompetition = competitionService.getById(id);
        ThrowUtils.throwIf(oldCompetition == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = competitionService.updateById(competition);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Competition> getCompetitionById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Competition competition = competitionService.getById(id);
        if (competition == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        // 不是本人或管理员，不能直接获取所有信息
        if (!competition.getCreatorId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(competition);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param competitionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<CompetitionVO>> listCompetitionVOByPage(@RequestBody CompetitionQueryRequest competitionQueryRequest, HttpServletRequest request) {
        long current = competitionQueryRequest.getCurrent();
        long size = competitionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Competition> competitionPage = competitionService.page(new Page<>(current, size),
                competitionService.getQueryWrapper(competitionQueryRequest));
        return ResultUtils.success(competitionService.getCompetitionVOPage(competitionPage, request));
    }

    /**
     * 分页获取题目列表（仅管理员）
     *
     * @param competitionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Competition>> listCompetitionByPage(@RequestBody CompetitionQueryRequest competitionQueryRequest,
                                                           HttpServletRequest request) {
        long current = competitionQueryRequest.getCurrent();
        long size = competitionQueryRequest.getPageSize();
        Page<Competition> competitionPage = competitionService.page(new Page<>(current, size),
                competitionService.getQueryWrapper(competitionQueryRequest));
        return ResultUtils.success(competitionPage);
    }



}
